package cn.wenhaha.app.log;

import ch.qos.logback.core.OutputStreamAppender;
import ch.qos.logback.core.joran.spi.ConsoleTarget;
import cn.wenhaha.common.config.Global;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.OutputStream;

import static java.lang.Thread.currentThread;

public class SocketAppender<E> extends OutputStreamAppender<E> {

    protected ConsoleTarget target = ConsoleTarget.SystemOut;


    @Override
    public void start() {
        final ClassLoader classLoader = Global.class.getClassLoader();
        currentThread().setContextClassLoader(classLoader);
        setOutputStream(new MyOutSteam());
        super.start();
    }


    public static class MyOutSteam extends OutputStream {


        public  void sendMessage(String message){
            LogSocketHandler.sendTextMessage(message);
        }


        @Override
        public void write(int b) throws IOException {
            System.out.println(b);
        }

        @Override
        public void write(@NotNull byte[] b) throws IOException {
            sendMessage(new String(b));
        }

        @Override
        public void write(@NotNull byte[] b, int off, int len) throws IOException {
            System.out.write(b, off, len);
        }
    }
}
